package com.java.simple.study.juc.pattern;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

/**
 * @author zhoujl
 * @date 2022/5/9 16:33
 * @desc
 */
@Slf4j(topic = "c.TestGuardedObject")
public class TestGuardedObject {

    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        new Thread(() -> {
            try {
                List<String> download = Downloader.download();
                log.debug("download complete");
                guardedObject.complete(download);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
        log.debug("waiting....");
        // 主线程阻塞等待
        Object response = guardedObject.get();
        log.debug("get response size:[{}]", ((List<String>) response).size());
    }


}

class GuardedObject {
    private Object response;
    private final Object lock = new Object();

    public Object get() {
        synchronized (lock) {
            while (response == null) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
    }

    public void complete(Object response) {
        synchronized (lock) {
            this.response = response;
            lock.notifyAll();
        }
    }

}
